#include "util.h"
#include "debug.h"
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "socket_helper.h"
#include <string.h>

int create_server_socket(int port) {
	int		   server_sock, optval;
	struct sockaddr_in server_addr;

	if ((server_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		return -SERVER_SOCKET_ERROR;
	}

	if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &optval,
		       sizeof(optval))
	    < 0) {
		return -SERVER_SETSOCKOPT_ERROR;
	}

	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family      = AF_INET;
	server_addr.sin_port	= htons(port);
	server_addr.sin_addr.s_addr = INADDR_ANY;

	if (bind(server_sock, ( struct sockaddr* )&server_addr,
		 sizeof(server_addr))
	    != 0) {
		    perror("bind : ");
		return -SERVER_BIND_ERROR;
	}

	if (listen(server_sock, 20) < 0) {
		return -SERVER_LISTEN_ERROR;
	}

	return server_sock;
}


int connect_with_remote(const char* host, int port) {
	struct sockaddr_in server_addr;
	int		   sockfd;

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		err_printf("create socket error!\n");
		return -1;
	}

	bzero(&server_addr, sizeof(struct sockaddr_in));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port   = htons(port);
	server_addr.sin_addr =
		*( struct in_addr* )gethostbyname(host)->h_addr_list[ 0 ];

	if (connect(sockfd, ( struct sockaddr* )(&server_addr),
		    sizeof(struct sockaddr))
	    == -1) {
		err_printf("connect error\n");
		return -2;
	}

	return sockfd;
}